<template>
  <div class="login-form">
    <el-form ref="ruleFormRef" :model="loginForm" :rules="rules" status-icon>
      <h3 class="form-title">后台管理系统</h3>
      <el-form-item prop="username">
        <el-input
          :prefix-icon="Avatar"
          placeholder="账号"
          type="text"
          v-model="loginForm.username"
        />
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          :prefix-icon="Lock"
          placeholder="密码"
          type="password"
          v-model="loginForm.password"
        />
      </el-form-item>
      <el-form-item>
        <el-button class="login-button" type="primary" @click="loginSubmit(ruleFormRef)"
          >登录</el-button
        >
      </el-form-item>
    </el-form>
    <div class="copyright">
      <span>Copyright © 2025-2025 Dr. Zhang All Rights Reserved.</span>
    </div>
  </div>
</template>

<script lang="ts">
export default {
  name: 'Login',
}
</script>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { Avatar, Lock } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import type { LoginParam } from '@/types/param'
import { getUserInfo, login } from '@/http/api'
import router from '@/router/index'
import { useUserStore } from '@/stores/userStore'

const userStore = useUserStore()
const ruleFormRef = ref<FormInstance>()
const loginForm = reactive<LoginParam>({
  username: 'admin',
  password: 'admin123',
})
const rules = reactive<FormRules<LoginParam>>({
  username: [{ required: true, message: '请输入您的账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入您的密码', trigger: 'blur' }],
})

const loginSubmit = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid, fields) => {
    if (valid) {
      login(loginForm)
        .then(async (res) => {
          if (res.code === 200) {
            userStore.setToken(res.data)
            await getUserInfo().then((res) => {
              userStore.setUserInfo(res.data)
            })
            router.push({ name: 'index' })
          }
        })
        .catch(() => {
          console.log('登录失败')
        })
    } else {
      console.log('error submit!', fields)
    }
  })
}
</script>

<style lang="scss" scoped>
.login-form {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-image: url('@/assets/img/login-bg.png');
}
.form-title {
  margin: 0 auto 30px auto;
  text-align: center;
}
.el-form {
  width: 400px;
  padding: 25px 25px 5px 25px;
  background-color: #fff;
  border-radius: 6px;
}
.el-form-item {
  padding: 0 25px;
  margin: 0 auto 30px auto;
}
.login-button {
  width: 100%;
}
.copyright {
  position: fixed;
  bottom: 5px;
  color: #fff;
}
</style>
